package com.baorant.seckillfront.controllers;

import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.UUID;

import com.baorant.seckillfront.service.ISenderService;
import com.baorant.seckillfront.service.TokensLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/Order")
public class OrderController {
	@Autowired
	TokensLimiter tokensLimiter;
	@Autowired
	private StringRedisTemplate template;
	@Autowired
	private ISenderService sendService;
	private String goodsid;

	@RequestMapping("/query_result")
	@ResponseBody
	public String query_result(String ticket) {
		String result = template.opsForValue().get("seckill.result." + ticket.trim());
		System.out.println(ticket + ":" + result);
		//删除处理结果
		template.delete("seckill.result." + ticket.trim());
		if (result != null && result.compareTo("ok") == 0) {
			// 将需要发送的消息封装为Message对象
			/*
			 * String msg = "seckillresult_" + goodsid + ", " + ticket; Message message =
			 * MessageBuilder.withPayload(msg.getBytes()).build();
			 * sendService.saveResult().send(message);
			 */
			return "ok";
		} else
			return result;
	}

	@RequestMapping("/buy")
	public String buy(int goodsid, Model m) {
		if (tokensLimiter.acquire()) {
			String starttime = template.opsForValue().get("seckill.starttime");
			System.out.println(starttime);
			SimpleDateFormat bjSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 北京
			bjSdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 设置北京时区
			String strNow = bjSdf.format(System.currentTimeMillis());
			System.out.println("北京时间：" + strNow);
			if (starttime != null && strNow.compareTo(starttime) < 0)
				return "waiting";
			UUID uuid = UUID.randomUUID();
			String msg = "seckillapply_" + goodsid + ", " + uuid.toString();
			// 将需要发送的消息封装为Message对象
			Message message = MessageBuilder.withPayload(msg.getBytes()).build();
			sendService.apply().send(message);
			m.addAttribute("ticket", uuid.toString());
			m.addAttribute("goodsid", goodsid);
			return "buy";
		} else
			return "busy";
	}
}
